package com.jy.rhin.domain.document.filter.impl;

import com.jy.api.patient.PatientAPI;
import com.jy.api.patient.dto.BingRenXXDto;
import com.jy.common.StringUtil;
import com.jy.rhin.domain.document.filter.DocumentFilter;
import com.jy.rhin.domain.document.filter.DocumentFilterContext;
import com.jy.rhin.domain.document.filter.DocumentFilterContextData;
import com.jy.rhin.domain.document.filter.DocumentFilterDescEnum;
import com.jy.rhin.domain.exception.RhinInfraErrorType;
import com.jy.rhin.infra.uitl.Asserts;
import com.jy.rhin.sdk.dto.document.DocumentContentDto;
import com.jy.rhin.sdk.dto.document.DocumentEntryDto;
import com.jy.rhin.sdk.dto.document.DocumentSubmissionSetDto;
import com.jy.rhin.sdk.dto.document.PatientDomainDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author MaYuXuan
 * @date 2022年6月9日 08:45:19
 * @Description 患者信息匹配校验
 */
@Slf4j
@Service
public class DocumentFilter4PatientUniqueness implements DocumentFilter {
    @Resource
    PatientAPI patientApi;

    @Override
    public boolean shouldFilter(DocumentSubmissionSetDto submissionSet, List<DocumentContentDto> contentList) {
        return true;
    }

    /**
     * 验证患者信息是否匹配正确
     *
     * @param submissionSet
     * @param contentList
     */
    @Override
    public void doFilter(DocumentSubmissionSetDto submissionSet, List<DocumentContentDto> contentList) {
        PatientDomainDto patientDomain = submissionSet.getPatientDomain();
        //验证提交集/文档条目/文件夹中所有patientId是否相同
        List<DocumentEntryDto> entries = submissionSet.getEntries();
        //List<DocumentFolderDto> folders = submissionSet.getFolders();
        Asserts.isFalse(entries.stream().anyMatch(entry -> !entry.getPatientDomain().equals(patientDomain)), RhinInfraErrorType.SUBMISSION_PATIENT_ERROR);
        //Asserts.isFalse(folders.stream().anyMatch(folder -> !folder.getPatientDomain().equals(patientDomain)), RhinInfraErrorType.SUBMISSION_PATIENT_ERROR);
        //通过patientId，调用EMPI接口获取用户信息，验证文档条目中患者基本信息是否匹配
        //Result<BingRenXXDto> byAppIdAndEid = patientApi.findByAppIdAndEid(patientDomain.getAppid(), patientDomain.getPatientId());
        //BingRenXXDto data = byAppIdAndEid.getData();
        //Asserts.nonNull(data, RhinInfraErrorType.PATIENT_ID_NOT_EXISTS);
        BingRenXXDto bingRenXX = new BingRenXXDto();
        if(StringUtil.isNullOrEmpty(patientDomain.getPatientId())){
        	Asserts.isFalse(true, RhinInfraErrorType.PATIENT_ID_NOT_EXISTS);
        }
        bingRenXX.setEid(patientDomain.getPatientId());
        bingRenXX.setAppId(patientDomain.getAppid());
        String patientId = patientApi.insertOrUpdate(bingRenXX);
        DocumentFilterContext.set(DocumentFilterContextData::setPatientMpi, patientId);
    }

    @Override
    public DocumentFilterDescEnum filterDesc() {
        return DocumentFilterDescEnum.PATIENT_UNIQUENESS;
    }

}
